package org.ccahouse.ccatrain.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.ccahouse.ccacommons.common.GlobalException;
import org.ccahouse.ccacommons.service.IRedisService;
import org.ccahouse.ccacommons.utils.StringUtils;
import org.ccahouse.ccatrain.dto.UserDto;
import org.ccahouse.ccatrain.dto.UserListDto;
import org.ccahouse.ccatrain.dto.UserListPageDto;
import org.ccahouse.ccatrain.entity.User;
import org.ccahouse.ccatrain.mapper.UserMapper;
import org.ccahouse.ccatrain.service.IUserService;
import org.ccahouse.ccacommons.common.PageResult;
import org.ccahouse.ccacommons.common.RestResult;
import org.ccahouse.ccacommons.common.ResultUtils;
import org.ccahouse.ccatrain.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kevin
 * @since 2020-07-04
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    IRedisService redisService;

    @Override
    public RestResult getUserPage(UserListPageDto param) {
        log.info("分页查询用户, 参数：{}", JSON.toJSON(param));

        User user = new User();
        String state = user.getState();
        if ("上海".equals(state)) {
            System.out.println("awefawefwaefawef");
        }

        PageResult<User> userList = param.startPage();
        this.baseMapper.selectList(new QueryWrapper<User>().lambda()
                .eq(User::getState, param.getState()));
        return ResultUtils.successPage(userList.getTotal(), userList.getResult());
    }


    @Override
    public RestResult getUserList(UserListDto param) {
        log.info("查询全部用户信息, 参数：{}", JSON.toJSON(param));
        String uStr = (String) redisService.getObject("train:users");
        List<User> users = JSON.parseArray(uStr, User.class);
        if (CollectionUtils.isEmpty(users)) {
            users = this.baseMapper.selectList(new QueryWrapper<User>().select("orgName", "account")
                    .eq("state", "上海"));
        }
        redisService.setObject("train:test", JSON.toJSONString(users), 36000L);
        return ResultUtils.success(users);
    }

    public RestResult getUserById(Integer id) {
        log.info("查询用户详情, 参数：{}", id);
        User user = super.getById(id);
        return ResultUtils.success(user);
    }

    @Override
    public RestResult saveUser(UserDto user) {
        User u = new User();
        BeanUtils.copyProperties(user, u);
        super.save(u);
        return ResultUtils.success();
    }

    @Override
    public RestResult saveUsers(List<UserDto> users) {
        log.info("批量新增用户， 参数：{}", JSON.toJSONString(users));

        List<User> us = users.stream().map(i -> {
            User u = new User();
            BeanUtils.copyProperties(i, u);
            return u;
        }).collect(Collectors.toList());
        super.saveBatch(us);
        return ResultUtils.success();
    }

    @Override
    public RestResult updateUserById(UserDto user) {
        User u = new User();
        BeanUtils.copyProperties(user, u);
        super.updateById(u);
        return ResultUtils.success();
    }

    @Override
    public RestResult updateUsersById(List<UserDto> users) {
        log.info("批量更新用户，参数：{}", JSON.toJSONString(users));
        List<User> us = users.stream().map(i -> {
            User u = new User();
            BeanUtils.copyProperties(i, u);
            return u;
        }).collect(Collectors.toList());
        super.updateBatchById(us);
        return ResultUtils.success();
    }

    @Override
    public RestResult updateUser(UserDto user) {
        log.info("更新用户，参数：{}", JSON.toJSONString(user));
        LambdaUpdateWrapper<User> lambda = new UpdateWrapper<User>().lambda();
        if (StringUtils.isNotEmpty(user.getOrgName())) {
            lambda.set(User::getOrgName, user.getOrgName());
        }
        lambda.set(User::getPssd, user.getPssd());
        lambda.eq(User::getAccount, user.getAccount());
        GlobalException exception = new GlobalException("更新失败");
        RestResult result = super.update(lambda) ? ResultUtils.success() : ResultUtils.error();
        return result;
    }

    @Override
    public RestResult saveOrUpdateUsers(List<UserDto> users) {
        log.info("批量插入或批量更新用户, 参数：{}", JSON.toJSONString(users));
        List<User> us = users.stream().map(i -> {
            User u = new User();
            BeanUtils.copyProperties(i, u);
            return u;
        }).collect(Collectors.toList());
        super.saveOrUpdateBatch(us);
        return ResultUtils.success();
    }

    public RestResult getUesrByParam(Integer id) {
        UserVo user = this.baseMapper.getUesrByParam(id, "上海");
        return ResultUtils.success(user);
    }

    @Override
    public RestResult getUsersByIds(List<Integer> ids) {
        List<UserVo> users = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(ids)) {
            users = this.baseMapper.getUsersByIds(ids);
        }
        return ResultUtils.success(users);
    }

    @Override
    public RestResult saveUsers2(List<UserDto> users) {
        this.baseMapper.saveUsers(users);
        return ResultUtils.success();
    }
}
